import { userState } from './user'
import config  from '@/config'
import request from '@/utils/request'

// 微信登录
export async function wxLogin() {
	try {
		// 获取微信登录凭证
		const loginRes = await uni.login()
		if (!loginRes.code) {
			throw new Error('获取登录凭证失败')
		}
		
		// 调用后端登录接口
		const loginResult = await uni.request({
			url: `${config.apiBaseUrl}/api/wechat/login`,
			method: 'POST',
			data: {
				code: loginRes.code
			}
		})
		console.log({loginResult});
        
		if (loginResult.statusCode !== 200 || loginResult.data.code != 200) {
			throw new Error(loginResult.data.message || '登录失败')
		}
		
		// 保存token
		const token = loginResult.data.data.token
		uni.setStorageSync('token', token)
		
		return token
	} catch (error) {
		console.error('微信登录失败:', error)
		throw error
	}
}

// 获取用户信息
export async function getUserInfo() {
	try {
		const token = uni.getStorageSync('token')
		if (!token) {
			throw new Error('未登录')
		}
		console.log(token,111);
		const userInfoResult = await uni.request({
			url: `${config.apiBaseUrl}/api/wechat/user/info`,
			method: 'GET',
			header: {
				'Authorization': token
			}
		})
		
		if (userInfoResult.statusCode !== 200 || userInfoResult.data.code != 200) {
			throw new Error(userInfoResult.data.message || '获取用户信息失败')
		}
		console.log({userInfoResult});
		
		// 更新用户状态
		userState.value = {
			...userState.value,
			...userInfoResult.data.data,
			isLoggedIn: true
		}
		
		return userInfoResult.data.data
	} catch (error) {
		console.error('获取用户信息失败:', error)
		throw error
	}
}

// 检查登录状态
export function checkLoginStatus() {
	const token = uni.getStorageSync('token')
	return !!token
}

// 退出登录
export function logout() {
	uni.removeStorageSync('token')
	userState.value = {
		...userState.value,
		isLoggedIn: false
	}
} 

// 发送消息
export function sendCustomerServiceMessage(data) {
	return request.post('wechat/customer_service/send', data)
}
